package router

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtimer"
	"text/app/api"
	"text/app/api/hello"
	"text/library/re"
	"text/library/swagger"
	"time"
)

func MiddlewareAuth(r *ghttp.Request) {
	token := r.Header.Get("Authorization")
	g.Log().Infof("token:%s", token)
	r.Middleware.Next()

}

func MiddlewareCORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

func init() {
	s := g.Server()
	swaggerPrefix := "/text"                                             //修改这里让nginx也可以转发swagger
	s.Plugin(&swagger.Swagger{Prefix: swaggerPrefix, BasicPath: "/api"}) //swagger插件
	//, BasicAuthUser: "qijin", BasicAuthPass: "qijin.keji"
	s.BindStatusHandler(404, func(r *ghttp.Request) {
		r.Response.ClearBuffer()
		r.Response.WriteTplContent(re.Content404, g.Map{"ERR": "ERR_API_PATH_NOT_FOUND", "RequestURI": r.RequestURI, "Method": r.Method, "Title": "404 Not Found", "Desc": "接口地址错误"})
	})
	s.BindStatusHandler(405, func(r *ghttp.Request) {
		r.Response.ClearBuffer()
		r.Response.WriteTplContent(re.Content404, g.Map{"ERR": "ERR_METHOD_NOT_ALLOWED", "RequestURI": r.RequestURI, "Method": r.Method, "Title": "405 Method Not Allowed", "Desc": "不支持的请求方式"})
	})
	//s.EnablePProf("/text/pprof") //性能调试

	s.SetAccessLogEnabled(false) //请求日志
	s.SetErrorLogEnabled(true)   //错误日志
	s.Use(MiddlewareCORS)

	//访问直接跳转到swagger
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.ALL("/", func(r *ghttp.Request) {
			r.Response.RedirectTo(swaggerPrefix + "/swagger")
		})
		//group.ALL("/pprof", func(r *ghttp.Request) {
		//	r.Response.RedirectTo(swaggerPrefix + "/pprof")
		//})
	})

	// 以/text/api 方式来定义路由, 让nginx转发文档更加方便
	s.Group("/api", func(group *ghttp.RouterGroup) {
		group.ALL("/hello", hello.Hello)
		//从这里开始
		//大屏
		group.GET("/DaPingGetList", api.DaPingGetList)
		group.GET("/DaPingGetModel", api.DaPingGetModel)
		group.GET("/DaPingGetVote", api.DaPingGetVote)
		group.POST("/DaPingCreate", api.DaPingCreate)
		group.PUT("/DaPingUpdate", api.DaPingUpdate)
		group.PUT("/DaPingVoteUpdate", api.DaPingVoteUpdate)
		group.DELETE("/DaPingDelete", api.DaPingDelete)
		group.DELETE("/DaPingDeletes", api.DaPingDeletes)
		group.GET("/Qrcode", api.Qrcode)
	})

	//启动后打开swagger页面
	gtimer.AddOnce(time.Second, func() {
		fmt.Println("提示: 点击打开 http://localhost" + g.Cfg().GetString("server.Address") + "/ 访问文档")
	})
}
